<?php

namespace app\trait;

use app\constant\CommonConstant;
use app\helpers\FormatHelper;
use app\helpers\UtilHelper;
use app\model\Address;
use app\model\Customer;
use app\model\LineItems;
use app\model\Orders;
use app\model\ShippingLines;
use Carbon\Carbon;
use think\helper\Arr;
use think\helper\Str;
use think\Request;

trait OrderTrait
{

    /**
     * @param Request $request
     * @return array
     * @desc 格式化订单数据
     */
    protected function formatOrderData(Request $request):array
    {
        $checkout = $request->param('checkout',[]);
        $shipping_line = $request->param('shipping_line',[]);
        $shipping_address = $request->param('shipping_address',[]);
        $items_subtotal_price = Arr::get($checkout,'cart.items_subtotal_price', '0.00');
        $items_subtotal_price = $items_subtotal_price > 0 ? bcdiv((string)$items_subtotal_price,'100',2) : '0.00';
        $total_price = Arr::get($checkout,'cart.total_price', '0.00');
        $total_price = $total_price > 0 ? bcdiv((string)$total_price,'100',2) : '0.00';
        $total_discount = Arr::get($checkout,'cart.total_discount', '0.00');
        $total_discount = $total_discount > 0 ? bcdiv((string)$total_discount,'100',2) : '0.00';
        $shipping_price = Arr::get($shipping_line,'price', '0.00');
        $total_price = bcadd($total_price,$shipping_price,2);
        $mainData = [
            'is_paypal_kj'=>$request->param('is_paypal_kj',Orders::IS_PAYPAL_KJ_N),
            'discount_codes'=>Arr::get($checkout,'discount_codes',[]),
            'order_type'=>Orders::ORDER_DRAFT,
            'shop_id'=>request()->middleware('x_shop_id'),
            'email'=>$request->param('email',''),
            'present_currency'=>Arr::get($checkout,'cart.currency','USD'),
            'currency_rate'=>Arr::get($checkout,'cart.currency_rate',1.00),
            'shipping_protection'=>$request->param('shipping_protection','0.00'),
            'checkout_id'=>$request->param('checkout_id',''),
            'phone'=>Arr::get($shipping_address,'phone',''),
            'subtotal_present'=>$items_subtotal_price,
            'total_present'=>$total_price,
            'discount_present'=>$total_discount,
            'shipping_price_present'=>$shipping_price,
            'shipping_name'=>Arr::get($shipping_line,'title', ''),
            'ip'=>UtilHelper::getClientIP(),
            'payment_token'=>[],
        ];
        $refererParams = FormatHelper::getCampaignParams($request);
        return array_merge($mainData,$refererParams);
    }


    /**
     * @return Orders $order
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @dec 保存订单
     */
    protected function saveOrder(Request $request,Orders $order = null)
    {
        $draftOrder = null;
        try {
            $orderData = $this->formatOrderData($request);
            $checkout = $request->param('checkout',[]);
            # 存cartLineItems
            $lineItems = Arr::get($checkout,'cart.items',[]);
            $items = $this->formatCartLineItems($lineItems);
            $addresses = $this->formatAddress($request);
            if(is_null($order)) {
                $orderData['created_at'] = Carbon::now()->subHours(16)->toDateTimeString();
                $draftOrder = Orders::create($orderData);
            }else{
                $orderData['updated_at'] = Carbon::now()->subHours(16)->toDateTimeString();
                $order->save($orderData);
                $draftOrder = $order;
            }
            # 先删除,后添加
            if($addresses){
                $addresses = (new Address())->fill($addresses)->getDatas();
                $draftOrder->addresses()->delete();
                $draftOrder->addresses()->saveAll($addresses);
            }
            if($items){
                $items = (new LineItems())->fill($items)->getDatas();
                $draftOrder->items()->delete();
                $draftOrder->items()->saveAll($items);
            }
            return $draftOrder;
        }catch (\Exception $e){
            if($draftOrder) Orders::saveExceptionMessage($draftOrder,$e->getMessage());
            throw new \Exception($e->getMessage());
        }
    }

    protected function formatOrderNo($shopId,$orderNo)
    {
        $shopId = $shopId < 10 ? '0' . $shopId : $shopId ;
        $time = date("His");
        $orderNo = str_replace('#','',$orderNo);
        return sprintf('#%s%s%s',$shopId,$orderNo,$time);
    }


    //格式化购物车列表
    protected function formatCartLineItems(array $lineItems)
    {
        foreach ($lineItems as $index => $item){
            $item['variant_title'] = ['title'=>$item['variant_title'] ?: $item['title']];
            $item['title'] = ['title'=>$item['title']];
            $item['sku'] = $item['sku'] ?: $item['variant_id'];
            $item['price'] = $item['presentment_price'];
            unset($item['id']);
            $goodsList[] = $item;
        }

        return $goodsList;
    }


    protected function formatAddress(Request $request)
    {
     $addresses = [];
      //正常支付
      $addr = $request->param('shipping_address',[]);
      if(empty($addr)) return $addresses;
      $addr['name'] = sprintf("%s %s",Arr::get($addr,'first_name'),Arr::get($addr,'last_name'));
      $billingAddress = $shippingAddress = $addr;
      if($request->has('billing_address')) $billingAddress = $request->param('billing_address');
        if ($shippingAddress) {
            $shippingAddress['type'] = Address::SHIPPING_ADDRESS;
            $addresses[] = $shippingAddress;
        }
        if ($billingAddress) {
            $billingAddress['type'] = Address::BILLING_ADDRESS;
            $addresses[] = $billingAddress;
        }
        return $addresses;
    }





}